const API_KEY = 'sk-d4627113e6a742cc90c47681d6b5d423';
const API_URL = 'https://api.deepseek.com/v1/chat/completions';

let chats = [];
let currentChatId = null;

// 初始化
function init() {
    // 从localStorage加载对话历史
    const savedChats = localStorage.getItem('chats');
    if (savedChats) {
        chats = JSON.parse(savedChats);
        renderChatList();
    }

    if (chats.length === 0) {
        createNewChat();
    } else {
        loadChat(chats[0].id);
    }
}

// 创建新对话
function createNewChat() {
    const newChat = {
        id: Date.now(),
        title: '新对话',
        messages: []
    };
    chats.unshift(newChat);
    saveChats();
    renderChatList();
    loadChat(newChat.id);
}

// 删除对话
function deleteChat(chatId) {
    const index = chats.findIndex(chat => chat.id === chatId);
    if (index !== -1) {
        chats.splice(index, 1);
        saveChats();
        renderChatList();
        if (chats.length === 0) {
            createNewChat();
        } else {
            loadChat(chats[0].id);
        }
    }
}

// 加载对话
function loadChat(chatId) {
    currentChatId = chatId;
    const chat = chats.find(c => c.id === chatId);
    if (chat) {
        document.getElementById('chat-container').innerHTML = '';
        chat.messages.forEach(msg => {
            appendMessage(msg.role, msg.content);
        });
        // 更新活动状态
        document.querySelectorAll('.chat-item').forEach(item => {
            item.classList.remove('active');
            if (item.dataset.id === chatId.toString()) {
                item.classList.add('active');
            }
        });
    }
}

// 渲染对话列表
function renderChatList() {
    const chatList = document.getElementById('chat-list');
    chatList.innerHTML = chats.map(chat => `
        <div class="chat-item ${chat.id === currentChatId ? 'active' : ''}" data-id="${chat.id}" onclick="loadChat(${chat.id})">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M8 12H8.01M12 12H12.01M16 12H16.01M21 12C21 16.418 16.97 20 12 20C10.5 20 9.077 19.692 7.8 19.14L3 20L4.3 15.9C3.305 14.604 3 13.31 3 12C3 7.582 7.03 4 12 4C16.97 4 21 7.582 21 12Z" 
                    stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            ${chat.title}
            <button class="delete-chat" onclick="event.stopPropagation(); deleteChat(${chat.id})">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M19 7L18.1327 19.1425C18.0579 20.1891 17.187 21 16.1378 21H7.86224C6.81296 21 5.94208 20.1891 5.86732 19.1425L5 7M10 11V17M14 11V17M15 7V4C15 3.44772 14.5523 3 14 3H10C9.44772 3 9 3.44772 9 4V7M4 7H20" 
                        stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </button>
        </div>
    `).join('');
}

// 保存对话到localStorage
function saveChats() {
    localStorage.setItem('chats', JSON.stringify(chats));
}

// 自动调整文本框高度
function autoResize(textarea) {
    textarea.style.height = 'auto';
    textarea.style.height = textarea.scrollHeight + 'px';
}

// 添加一个显示加载消息的函数
function showLoadingMessage() {
    const chatContainer = document.getElementById('chat-container');
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message assistant-message loading-message';
    messageDiv.id = 'loading-message';

    const avatar = document.createElement('div');
    avatar.className = 'message-avatar';
    avatar.innerHTML = 'A';

    const messageContent = document.createElement('div');
    messageContent.className = 'message-content';

    const loadingDots = document.createElement('div');
    loadingDots.className = 'loading-dots';
    loadingDots.innerHTML = `
        <div class="loading-dot"></div>
        <div class="loading-dot"></div>
        <div class="loading-dot"></div>
    `;

    messageContent.appendChild(document.createTextNode('thinking......'));
    messageContent.appendChild(loadingDots);

    messageDiv.appendChild(avatar);
    messageDiv.appendChild(messageContent);
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 移除加载消息
function removeLoadingMessage() {
    const loadingMessage = document.getElementById('loading-message');
    if (loadingMessage) {
        loadingMessage.remove();
    }
}

// 修改发送消息函数
async function sendMessage() {
    const messageInput = document.getElementById('message-input');
    const message = messageInput.value.trim();
    if (!message) return;

    // 清空输入框
    messageInput.value = '';
    messageInput.style.height = 'auto';

    // 添加用户消息
    appendMessage('user', message);

    // 保存消息到当前对话
    const currentChat = chats.find(c => c.id === currentChatId);
    if (currentChat) {
        currentChat.messages.push({ role: 'user', content: message });
        // 如果是第一条消息，更新对话标题
        if (currentChat.messages.length === 1) {
            currentChat.title = message.slice(0, 30) + (message.length > 30 ? '...' : '');
            renderChatList();
        }
    }

    // 显示加载消息
    showLoadingMessage();

    try {
        const response = await axios.post(API_URL, {
            messages: [
                { role: "system", content: "You are a helpful assistant." },
                { role: "user", content: message }
            ],
            model: "deepseek-chat",
        }, {
            headers: {
                'Authorization': `Bearer ${API_KEY}`,
                'Content-Type': 'application/json'
            }
        });

        // 移除加载消息
        removeLoadingMessage();

        const assistantMessage = response.data.choices[0].message.content;
        appendMessage('assistant', assistantMessage);

        // 保存助手回复
        if (currentChat) {
            currentChat.messages.push({ role: 'assistant', content: assistantMessage });
            saveChats();
        }
    } catch (error) {
        // 移除加载消息
        removeLoadingMessage();

        console.error('Error:', error);
        appendMessage('assistant', '抱歉，发生了错误，请稍后重试。');
    }
}

// 添加消息到界面
function appendMessage(role, content) {
    const chatContainer = document.getElementById('chat-container');
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${role}-message`;

    const avatar = document.createElement('div');
    avatar.className = 'message-avatar';
    avatar.innerHTML = role === 'user' ? 'U' : 'A';

    const messageContent = document.createElement('div');
    messageContent.className = 'message-content';

    // 检测内容是否包含代码
    if (content.includes('```')) {
        // 分割内容，处理多个代码块
        const blocks = content.split('```');
        blocks.forEach((block, index) => {
            if (index % 2 === 0) {
                // 普通文本
                if (block.trim()) {
                    messageContent.appendChild(document.createTextNode(block.trim()));
                }
            } else {
                // 代码块
                const codeBlock = document.createElement('div');
                codeBlock.className = 'code-block';

                // 提取语言信息
                const firstLine = block.trim().split('\n')[0];
                const language = firstLine || 'plaintext';
                const code = block.replace(firstLine, '').trim();

                // 创建代码块头部
                const header = document.createElement('div');
                header.className = 'code-header';
                header.innerHTML = `
                    <span class="code-language">${language}</span>
                    <button class="copy-button" onclick="copyCode(this)">复制代码</button>
                `;

                // 创建代码内容
                const codeContent = document.createElement('div');
                codeContent.className = 'code-content';
                codeContent.innerHTML = `
                    <pre><code class="language-${language}">${escapeHtml(code)}</code></pre>
                `;

                codeBlock.appendChild(header);
                codeBlock.appendChild(codeContent);
                messageContent.appendChild(codeBlock);

                // 触发 Prism.js 语法高亮
                Prism.highlightElement(codeContent.querySelector('code'));
            }
        });
    } else {
        messageContent.textContent = content;
    }

    messageDiv.appendChild(avatar);
    messageDiv.appendChild(messageContent);
    chatContainer.appendChild(messageDiv);
    chatContainer.scrollTop = chatContainer.scrollHeight;
}

// 辅助函数：HTML转义
function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// 复制代码功能
function copyCode(button) {
    const codeBlock = button.closest('.code-block');
    const code = codeBlock.querySelector('code').textContent;

    navigator.clipboard.writeText(code).then(() => {
        const originalText = button.textContent;
        button.textContent = '已复制！';
        setTimeout(() => {
            button.textContent = originalText;
        }, 2000);
    }).catch(err => {
        console.error('复制失败:', err);
    });
}

// 添加回车发送功能
document.getElementById('message-input').addEventListener('keydown', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});

// 初始化应用
init();